#include "pt100_hx711.h"

#ifdef USE_PT1000
#define RMAX 1800
#define RMIN 800
#define BRI_MAX 4300000
#define BRI_MIN 1500000
#define RIN_MAX 365000
#define RIN_MIN -1580000
#else
#define RMAX 180
#define RMIN 18
#define BRI_MAX 7300000
#define BRI_MIN 1500000
#define RIN_MAX 365000
#define RIN_MIN -1580000
#endif


pt100_hx711::pt100_hx711(byte output_pin, byte clock_pin) {
    this->output_pin = output_pin;
    this->clock_pin = clock_pin;
}

void pt100_hx711::begin() {
    hx711 = new Q2HX711(output_pin, clock_pin);
    PT100 = new pt100rtd();
    hx711->begin();
    _state = -100;
}

void pt100_hx711::calc() {
    float Rb, s, uu, dd;
    int rr;

#ifdef USE_PT1000
    Rb = 1000;
    rin = (float)Rb * (2 * (float)db / ((float)da + (float)db) - 1);
#else
    Rb = 100;
    s = (float) da / (float) db;
    uu = (64 - s * 32 * 2);
    dd = (2 * s * 32 + 64);
    rin = (Rb * uu / dd);

#endif
    _state = 0;
    if ((hx711->db > BRI_MAX) || (rin > RMAX) || (hx711->db < BRI_MIN)) {
        _state = -1;
        if (rep++ > 200)
            t = 401;
    } else if ((hx711->da > RIN_MAX) || (rin < RMIN) || (hx711->da < RIN_MIN)) {
        _state = -2;
        if (rep++ > 200)
            t = -201;
    } else if (_state == 0) {
#ifdef USE_PT1000
        float val = ((3.9083 - sqrt(17.58480889 - 0.00231 * rin)) / 0.001155);
        if (t < -50)
            t = 50;
        if (t > 200)
            t = 200;
        // if (val > last && (val - last) > 5.0)
        //     val = last + 5;
        // else if (val < last && (last - val) > 5.0)
        //     val = last - 5;
        // t = last * 0.8 + val * 0.2;
        last = val;
        t = val;
#else
        t = PT100->celsius_cvd(rin);
#endif
        rr = (int) (rin * 100);
        rep = 0;
    }
}

void pt100_hx711::loop() {
    da = hx711->da;
    db = hx711->db;
}

float pt100_hx711::rvalue() { return rin; }

float pt100_hx711::value() {
    calc();
    auto v = (int) (t * 10);
    out_val = float(v) / 10;
    return out_val;
}

void pt100_hx711::set_factory(unsigned short i) {
    if (i < 500)i = 500;
    hx711->nrs = i / 100;   //ms转换采样次数

}
